import { createStore } from 'vuex';
import * as Api from "@/api/data";

export default createStore({
  state: {
    userInfo: {},
    isLogin: false, // 用户是否登录
    cart: [], // 购物车信息
    cartNumber: 0, // 购物车商品数
    goodsSpec: [], // 商品规格
    defaultAddress: '' // 默认收货地址
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_ISLOGIN: (state, val) => {
      state.isLogin = val;
    },
    SET_CART: (state, val) => {
      state.cart = val;
    },
    SET_CARTNUMBER: (state, val) => {
      state.cartNumber = val;
    },
    SET_GOODSSPEC: (state, val) => {
      state.goodsSpec = val;
    },
    SER_DEFAULTADDRESS: (state, val) => {
      state.defaultAddress = val;
    }
  },
  actions: {

    // 页面刷新时防止信息丢失可以掉用本地存储获取用户信息
    initUser({ commit, dispatch }) {
      let user = localStorage.getItem('userInfo');
      if (user) {
        let userInfo = JSON.parse(user);
        commit('SET_USERINFO', userInfo);
        commit('SET_ISLOGIN', true);
      }
      // 初始化购物车
      dispatch('initCart');
    },

    // 退出登录
    loginOut({ commit }) {
      localStorage.clear();
      commit('SET_USERINFO', {});
      commit('SET_ISLOGIN', false);
    },

    // 使用本地缓存功能存储购物车信息
    initCart({ commit, state, dispatch }) {
      // 如果是登录状态
      if (state.isLogin) {
        // 查询购物车商品数量
        dispatch('getCartNumber');
      } else {
        // 非登录状态
        let cart = sessionStorage.getItem('cart');
        if (cart) {
          let list = JSON.parse(cart);
          commit('SET_CART', list);
          commit('SET_CARTNUMBER', list.length);
        }
      }
    },

    // 查询购物车商品数量
    getCartNumber({ commit, state }) {
      Api.getCartNumber(state.userInfo.id).then(res => {
        commit('SET_CARTNUMBER', res);
      });
    },

    // 存储购物车信息
    addCart({ commit }, list) {
      commit('SET_CART', list);
      commit('SET_CARTNUMBER', list.length);
      sessionStorage.setItem('cart', JSON.stringify(list));
    },

    // 获取商品规格
    getGoodsSpec({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.goodsSpec.length > 0) {
          resolve(state.goodsSpec);
        } else {
          Api.goodsSpec().then(res => {
            resolve(res);
            commit('SET_GOODSSPEC', res);
          }).catch(e => { reject(e); });
        }
      });
    },

    // 获取默认收货地址
    getDefaultAddress({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.defaultAddress) {
          resolve(state.defaultAddress);
        } else {
          Api.getDefAddress().then(res => {
            if (res) {
              let nd = Object.assign(res);
              nd.name = res.consignee;
              commit('SER_DEFAULTADDRESS', res);
            }
            resolve(res);
          }).catch(e => { reject(e); });
        }
      });
    }

  },
  modules: {
  }
});
